#include "syntaxthememanager.h"
#include "nddsetting.h"
#include "styleset.h"
#include <QDebug>
#include <QProcess>
#include <QSettings>
#include <QGuiApplication>
#include <QDir>

SyntaxThemeManager* SyntaxThemeManager::s_instance = nullptr;

SyntaxThemeManager* SyntaxThemeManager::instance()
{
    if (s_instance == nullptr)
    {
        s_instance = new SyntaxThemeManager();
    }
    return s_instance;
}

SyntaxThemeManager::SyntaxThemeManager(QObject *parent)
    : QObject(parent)
    , m_currentThemeId(SYNTAX_LIGHT)
{
    initThemes();
    loadThemeFromSettings();
}

SyntaxThemeManager::~SyntaxThemeManager()
{
}

void SyntaxThemeManager::initThemes()
{
    initLightTheme();
    initDarkTheme();
    initSolarizedTheme();
    initMonokaiTheme();
    initDraculaTheme();
}

void SyntaxThemeManager::initLightTheme()
{
    QMap<QString, QColor> colors;
    
    // 编辑器背景和前景色
    colors["background"] = QColor(255, 255, 255);
    colors["foreground"] = QColor(0, 0, 0);
    colors["caret"] = QColor(0, 0, 0);
    colors["selection_bg"] = QColor(173, 214, 255);
    colors["selection_fg"] = QColor(0, 0, 0);
    
    // 行号列和边距
    colors["line_number_bg"] = QColor(240, 240, 240);
    colors["line_number_fg"] = QColor(128, 128, 128);
    colors["margin_bg"] = QColor(240, 240, 240);  // 行号和内容之间的空隙
    colors["fold_margin_fg"] = QColor(240, 240, 240);  // 折叠边距前景
    colors["fold_margin_bg"] = QColor(240, 240, 240);  // 折叠边距背景
    colors["bookmark_bg"] = QColor(236, 236, 236);     // 书签边距背景
    colors["fold_icon_fg"] = QColor(128, 128, 128);    // 折叠图标前景（方块颜色）
    colors["fold_icon_bg"] = QColor(255, 255, 255);    // 折叠图标背景
    colors["fold_icon_active"] = QColor(0, 0, 255);    // 折叠图标活动状态
    
    // 当前行和括号
    colors["current_line_bg"] = QColor(232, 232, 255);
    colors["brace_match_bg"] = QColor(0, 255, 0, 100);
    colors["brace_match_fg"] = QColor(0, 0, 0);
    colors["brace_unmatch_bg"] = QColor(255, 0, 0, 100);
    colors["brace_unmatch_fg"] = QColor(255, 255, 255);
    
    // 语法高亮颜色
    colors["comment"] = QColor(0, 128, 0);           // 注释 - 绿色
    colors["keyword"] = QColor(0, 0, 255);           // 关键字 - 蓝色
    colors["string"] = QColor(163, 21, 21);          // 字符串 - 红色
    colors["number"] = QColor(0, 128, 128);          // 数字 - 青色
    colors["operator"] = QColor(0, 0, 0);            // 操作符 - 黑色
    colors["identifier"] = QColor(0, 0, 0);          // 标识符 - 黑色
    colors["function"] = QColor(128, 0, 128);        // 函数 - 紫色
    colors["class"] = QColor(43, 145, 175);          // 类名 - 深蓝色
    colors["preprocessor"] = QColor(128, 128, 128);  // 预处理 - 灰色
    
    m_themeColors[SYNTAX_LIGHT] = colors;
}

void SyntaxThemeManager::initDarkTheme()
{
    QMap<QString, QColor> colors;
    
    // 编辑器背景和前景色 - 提高对比度
    colors["background"] = QColor(30, 30, 30);       // 更深的背景
    colors["foreground"] = QColor(230, 230, 230);    // 更亮的前景
    colors["caret"] = QColor(255, 255, 255);
    colors["selection_bg"] = QColor(75, 110, 175);
    colors["selection_fg"] = QColor(255, 255, 255);
    
    // 行号列和边距
    colors["line_number_bg"] = QColor(25, 25, 25);   // 比编辑器稍深
    colors["line_number_fg"] = QColor(150, 150, 150); // 更亮的行号
    colors["margin_bg"] = QColor(25, 25, 25);  // 行号和内容之间的空隙
    colors["fold_margin_fg"] = QColor(25, 25, 25);  // 折叠边距前景
    colors["fold_margin_bg"] = QColor(25, 25, 25);  // 折叠边距背景
    colors["bookmark_bg"] = QColor(25, 25, 25);     // 书签边距背景
    colors["fold_icon_fg"] = QColor(220, 220, 220); // 折叠图标前景（方块颜色）- 更亮
    colors["fold_icon_bg"] = QColor(80, 80, 80);    // 折叠图标背景 - 提高对比度
    colors["fold_icon_active"] = QColor(100, 180, 255); // 折叠图标活动状态
    
    // 当前行和括号
    colors["current_line_bg"] = QColor(45, 45, 45);  // 微妙的高亮，不刺眼
    colors["brace_match_bg"] = QColor(0, 128, 0, 100);
    colors["brace_match_fg"] = QColor(255, 255, 255);
    colors["brace_unmatch_bg"] = QColor(128, 0, 0, 100);
    colors["brace_unmatch_fg"] = QColor(255, 255, 255);
    
    // 语法高亮颜色 - 增强对比度，更易阅读
    colors["comment"] = QColor(96, 153, 76);        // 注释 - 绿色（更深，增强对比）
    colors["keyword"] = QColor(66, 146, 214);       // 关键字 - 亮蓝色（更鲜艳）
    colors["string"] = QColor(226, 135, 80);        // 字符串 - 橙色（更亮，更醒目）
    colors["number"] = QColor(141, 196, 148);       // 数字 - 浅绿色（更明亮）
    colors["operator"] = QColor(232, 232, 232);     // 操作符 - 亮白色（更清晰）
    colors["identifier"] = QColor(240, 240, 240);   // 标识符 - 明亮的白色（最亮）
    colors["function"] = QColor(230, 190, 100);     // 函数 - 金色（更醒目）
    colors["class"] = QColor(68, 181, 216);         // 类名 - 亮青色（更清晰）
    colors["preprocessor"] = QColor(199, 89, 217);  // 预处理 - 亮紫色（更鲜艳）
    
    m_themeColors[SYNTAX_DARK] = colors;
}

void SyntaxThemeManager::initSolarizedTheme()
{
    QMap<QString, QColor> colors;
    
    // Solarized Dark 配色方案
    colors["background"] = QColor(0, 43, 54);
    colors["foreground"] = QColor(131, 148, 150);
    colors["caret"] = QColor(147, 161, 161);
    colors["selection_bg"] = QColor(7, 54, 66);
    colors["selection_fg"] = QColor(147, 161, 161);
    
    colors["line_number_bg"] = QColor(7, 54, 66);
    colors["line_number_fg"] = QColor(88, 110, 117);
    colors["margin_bg"] = QColor(7, 54, 66);
    colors["fold_margin_fg"] = QColor(7, 54, 66);
    colors["fold_margin_bg"] = QColor(7, 54, 66);
    colors["bookmark_bg"] = QColor(7, 54, 66);
    colors["fold_icon_fg"] = QColor(147, 161, 161);  // 更亮的灰色
    colors["fold_icon_bg"] = QColor(42, 161, 152);   // 青色背景，更明显
    colors["fold_icon_active"] = QColor(181, 137, 0); // 金色活动状态
    colors["current_line_bg"] = QColor(7, 54, 66);
    colors["brace_match_bg"] = QColor(133, 153, 0, 100);
    colors["brace_match_fg"] = QColor(253, 246, 227);
    colors["brace_unmatch_bg"] = QColor(220, 50, 47, 100);
    colors["brace_unmatch_fg"] = QColor(253, 246, 227);
    
    colors["comment"] = QColor(88, 110, 117);
    colors["keyword"] = QColor(133, 153, 0);
    colors["string"] = QColor(42, 161, 152);
    colors["number"] = QColor(211, 54, 130);
    colors["operator"] = QColor(147, 161, 161);
    colors["identifier"] = QColor(131, 148, 150);
    colors["function"] = QColor(38, 139, 210);
    colors["class"] = QColor(181, 137, 0);
    colors["preprocessor"] = QColor(203, 75, 22);
    
    m_themeColors[SYNTAX_SOLARIZED] = colors;
}

void SyntaxThemeManager::initMonokaiTheme()
{
    QMap<QString, QColor> colors;
    
    // Monokai 配色方案
    colors["background"] = QColor(39, 40, 34);
    colors["foreground"] = QColor(248, 248, 242);
    colors["caret"] = QColor(248, 248, 240);
    colors["selection_bg"] = QColor(73, 72, 62);
    colors["selection_fg"] = QColor(248, 248, 242);
    
    colors["line_number_bg"] = QColor(39, 40, 34);
    colors["line_number_fg"] = QColor(117, 113, 94);
    colors["margin_bg"] = QColor(39, 40, 34);
    colors["fold_margin_fg"] = QColor(39, 40, 34);
    colors["fold_margin_bg"] = QColor(39, 40, 34);
    colors["bookmark_bg"] = QColor(39, 40, 34);
    colors["fold_icon_fg"] = QColor(248, 248, 242);  // 明亮的白色
    colors["fold_icon_bg"] = QColor(102, 217, 239);  // 青色背景，高对比度
    colors["fold_icon_active"] = QColor(166, 226, 46); // 亮绿色活动状态
    colors["current_line_bg"] = QColor(73, 72, 62);
    colors["brace_match_bg"] = QColor(166, 226, 46, 100);
    colors["brace_match_fg"] = QColor(39, 40, 34);
    colors["brace_unmatch_bg"] = QColor(249, 38, 114, 100);
    colors["brace_unmatch_fg"] = QColor(248, 248, 242);
    
    colors["comment"] = QColor(117, 113, 94);
    colors["keyword"] = QColor(249, 38, 114);
    colors["string"] = QColor(230, 219, 116);
    colors["number"] = QColor(174, 129, 255);
    colors["operator"] = QColor(249, 38, 114);
    colors["identifier"] = QColor(248, 248, 242);
    colors["function"] = QColor(166, 226, 46);
    colors["class"] = QColor(102, 217, 239);
    colors["preprocessor"] = QColor(174, 129, 255);
    
    m_themeColors[SYNTAX_MONOKAI] = colors;
}

void SyntaxThemeManager::initDraculaTheme()
{
    QMap<QString, QColor> colors;
    
    // Dracula 配色方案
    colors["background"] = QColor(40, 42, 54);
    colors["foreground"] = QColor(248, 248, 242);
    colors["caret"] = QColor(248, 248, 240);
    colors["selection_bg"] = QColor(68, 71, 90);
    colors["selection_fg"] = QColor(248, 248, 242);
    
    colors["line_number_bg"] = QColor(40, 42, 54);
    colors["line_number_fg"] = QColor(98, 114, 164);
    colors["margin_bg"] = QColor(40, 42, 54);
    colors["fold_margin_fg"] = QColor(40, 42, 54);
    colors["fold_margin_bg"] = QColor(40, 42, 54);
    colors["bookmark_bg"] = QColor(40, 42, 54);
    colors["fold_icon_fg"] = QColor(248, 248, 242);  // 明亮的白色
    colors["fold_icon_bg"] = QColor(139, 233, 253);  // 青色背景，高对比度
    colors["fold_icon_active"] = QColor(80, 250, 123); // 亮绿色活动状态
    colors["current_line_bg"] = QColor(68, 71, 90);
    colors["brace_match_bg"] = QColor(80, 250, 123, 100);
    colors["brace_match_fg"] = QColor(40, 42, 54);
    colors["brace_unmatch_bg"] = QColor(255, 85, 85, 100);
    colors["brace_unmatch_fg"] = QColor(248, 248, 242);
    
    colors["comment"] = QColor(98, 114, 164);
    colors["keyword"] = QColor(255, 121, 198);
    colors["string"] = QColor(241, 250, 140);
    colors["number"] = QColor(189, 147, 249);
    colors["operator"] = QColor(255, 121, 198);
    colors["identifier"] = QColor(248, 248, 242);
    colors["function"] = QColor(80, 250, 123);
    colors["class"] = QColor(139, 233, 253);
    colors["preprocessor"] = QColor(255, 184, 108);
    
    m_themeColors[SYNTAX_DRACULA] = colors;
}

void SyntaxThemeManager::setSyntaxTheme(int themeId)
{
    if (themeId < 0 || themeId >= SYNTAX_MAX)
    {
        qWarning() << "Invalid syntax theme ID:" << themeId;
        return;
    }
    
    if (m_currentThemeId != themeId)
    {
        m_currentThemeId = themeId;
        qDebug() << "Syntax theme changed to:" << getSyntaxThemeName(themeId);
        
        // 应用编辑器全局样式
        applyEditorGlobalStyle(themeId);
        
        saveThemeToSettings();
        emit syntaxThemeChanged(themeId);
    }
}

QString SyntaxThemeManager::getSyntaxThemeName(int themeId) const
{
    static const QString themeNames[SYNTAX_MAX] = {
        QStringLiteral("亮色代码"),
        QStringLiteral("暗色代码"),
        QStringLiteral("Solarized"),
        QStringLiteral("Monokai"),
        QStringLiteral("Dracula")
    };
    
    if (themeId >= 0 && themeId < SYNTAX_MAX)
        return themeNames[themeId];
    else
        return themeNames[SYNTAX_LIGHT];
}

QString SyntaxThemeManager::getCurrentSyntaxThemeName() const
{
    return getSyntaxThemeName(m_currentThemeId);
}

bool SyntaxThemeManager::isDarkSyntaxTheme(int themeId) const
{
    // 亮色语法主题返回false，其他都是暗色系
    return (themeId != SYNTAX_LIGHT);
}

bool SyntaxThemeManager::isCurrentDarkSyntaxTheme() const
{
    return isDarkSyntaxTheme(m_currentThemeId);
}

void SyntaxThemeManager::applyCurrentTheme()
{
    // 发出信号，通知所有编辑器更新语法高亮
    emit syntaxThemeChanged(m_currentThemeId);
}

void SyntaxThemeManager::loadThemeFromSettings()
{
    int savedThemeId = NddSetting::getKeyValueFromNumSets(SYNTAX_THEME_KEY);

    // 始终使用亮色语法主题，忽略之前的设置或系统主题
    if (savedThemeId != SYNTAX_LIGHT)
    {
        savedThemeId = SYNTAX_LIGHT;
        NddSetting::updataKeyValueFromNumSets(SYNTAX_THEME_KEY, savedThemeId);
        qDebug() << "Force syntax theme to light:" << getSyntaxThemeName(savedThemeId);
    }

    m_currentThemeId = savedThemeId;

    // 应用编辑器全局样式（启动时必须调用）
    applyEditorGlobalStyle(m_currentThemeId);

    qDebug() << "Loaded syntax theme from settings:" << getSyntaxThemeName(m_currentThemeId);
}

void SyntaxThemeManager::saveThemeToSettings()
{
    NddSetting::updataKeyValueFromNumSets(SYNTAX_THEME_KEY, m_currentThemeId);
    qDebug() << "Saved syntax theme to settings:" << getSyntaxThemeName(m_currentThemeId);
}

QColor SyntaxThemeManager::getThemeColor(int themeId, const QString& role) const
{
    if (themeId < 0 || themeId >= SYNTAX_MAX)
    {
        themeId = SYNTAX_LIGHT;
    }
    
    if (m_themeColors.contains(themeId) && m_themeColors[themeId].contains(role))
    {
        return m_themeColors[themeId][role];
    }
    
    // 返回默认颜色
    return QColor(0, 0, 0);
}

QColor SyntaxThemeManager::getCurrentThemeColor(const QString& role) const
{
    return getThemeColor(m_currentThemeId, role);
}

QColor SyntaxThemeManager::mapLightColorToCurrentTheme(const QColor& lightColor) const
{
    // 如果是亮色主题，直接返回原色
    if (m_currentThemeId == SYNTAX_LIGHT)
    {
        return lightColor;
    }
    
    int r = lightColor.red();
    int g = lightColor.green();
    int b = lightColor.blue();
    
    // 计算亮度 (0-255)，使用感知亮度公式
    int brightness = (r * 299 + g * 587 + b * 114) / 1000;
    
    // 纯黑色或极深色（亮度 < 30）→ 明亮白色
    if (brightness < 30)
    {
        return QColor(220, 220, 220, lightColor.alpha());
    }
    
    // 深色（亮度 < 128）→ 提亮处理
    if (brightness < 128)
    {
        // 使用更智能的提亮算法，保持色相
        // 计算与黑色的距离，然后在反方向提亮
        double brightnessFactor = 128.0 / qMax(brightness, 1);
        
        r = qMin(255, (int)(r * brightnessFactor * 1.8));
        g = qMin(255, (int)(g * brightnessFactor * 1.8));
        b = qMin(255, (int)(b * brightnessFactor * 1.8));
        
        // 确保最终亮度至少为 160（在暗色背景上可读）
        int newBrightness = (r * 299 + g * 587 + b * 114) / 1000;
        if (newBrightness < 160)
        {
            double boostFactor = 160.0 / newBrightness;
            r = qMin(255, (int)(r * boostFactor));
            g = qMin(255, (int)(g * boostFactor));
            b = qMin(255, (int)(b * boostFactor));
        }
        
        return QColor(r, g, b, lightColor.alpha());
    }
    
    // 中等亮度（128-200）→ 适度提亮
    if (brightness < 200)
    {
        double boostFactor = 1.2;
        r = qMin(255, (int)(r * boostFactor));
        g = qMin(255, (int)(g * boostFactor));
        b = qMin(255, (int)(b * boostFactor));
        return QColor(r, g, b, lightColor.alpha());
    }
    
    // 太亮的颜色（> 200）稍微降低，避免刺眼
    r = qMin(230, r);
    g = qMin(230, g);
    b = qMin(230, b);
    return QColor(r, g, b, lightColor.alpha());
}

void SyntaxThemeManager::applyEditorGlobalStyle(int themeId)
{
    // 将语法主题的颜色应用到 StyleSet 的全局样式中
    // 这样编辑器的背景、行号列等会跟随代码主题
    if (!StyleSet::s_global_style) return;
    
    // 编辑器背景和前景
    StyleSet::s_global_style->default_style.bgColor = getThemeColor(themeId, "background");
    StyleSet::s_global_style->default_style.fgColor = getThemeColor(themeId, "foreground");
    
    // 行号列
    StyleSet::s_global_style->line_number_margin.bgColor = getThemeColor(themeId, "line_number_bg");
    StyleSet::s_global_style->line_number_margin.fgColor = getThemeColor(themeId, "line_number_fg");
    
    // 当前行
    StyleSet::s_global_style->current_line_background_color.bgColor = getThemeColor(themeId, "current_line_bg");
    
    // 选中文本
    StyleSet::s_global_style->select_text_color.bgColor = getThemeColor(themeId, "selection_bg");
    StyleSet::s_global_style->select_text_color.fgColor = getThemeColor(themeId, "selection_fg");
    
    // 光标
    StyleSet::s_global_style->caret_colour.fgColor = getThemeColor(themeId, "caret");
    
    // 括号匹配
    StyleSet::s_global_style->brace_highight.bgColor = getThemeColor(themeId, "brace_match_bg");
    StyleSet::s_global_style->brace_highight.fgColor = getThemeColor(themeId, "brace_match_fg");
    
    // 括号不匹配
    StyleSet::s_global_style->bad_brace_color.bgColor = getThemeColor(themeId, "brace_unmatch_bg");
    StyleSet::s_global_style->bad_brace_color.fgColor = getThemeColor(themeId, "brace_unmatch_fg");
    
    // 更新边距背景色（行号和内容之间的空隙）
    StyleSet::marginsBackgroundColor = getThemeColor(themeId, "margin_bg");
    
    // 折叠边距颜色
    StyleSet::s_global_style->fold_margin.fgColor = getThemeColor(themeId, "fold_margin_fg");
    StyleSet::s_global_style->fold_margin.bgColor = getThemeColor(themeId, "fold_margin_bg");
    
    // 书签边距颜色
    StyleSet::s_global_style->bookmark_margin.bgColor = getThemeColor(themeId, "bookmark_bg");
    StyleSet::bookmarkBkColor = getThemeColor(themeId, "bookmark_bg");
    
    // 折叠图标颜色
    StyleSet::s_global_style->fold.fgColor = getThemeColor(themeId, "fold_icon_fg");
    StyleSet::s_global_style->fold.bgColor = getThemeColor(themeId, "fold_icon_bg");
    StyleSet::s_global_style->fold_active.fgColor = getThemeColor(themeId, "fold_icon_active");
    
    // 折叠标记颜色（用于QsciScintilla的API）
    StyleSet::foldfgColor = getThemeColor(themeId, "fold_icon_fg");
    StyleSet::foldbgColor = getThemeColor(themeId, "fold_icon_bg");
    
    qDebug() << "Applied editor global style from syntax theme:" << getSyntaxThemeName(themeId);
}

